/*
 * @Author: lanbin
 * @Date: 2020-02-16 18:01:50
 * @Last Modified by: lanbin1987@gmail.com
 * @Last Modified time: 2021-08-12 17:33:15
 */

const path = require('path');
const pageFolder = path.resolve('./src/views/');
const pages = {};
const fs = require('fs');

const CompressionWebpackPlugin = require('compression-webpack-plugin');
const isProduction = process.env.NODE_ENV === 'production';

function resolve(dir) {
  return path.join(__dirname, dir);
}

const PAGES = fs.readdirSync(pageFolder).map((name) => {
  const [_] = name.split('.');
  const LOWER_CASE = _.toLowerCase();

  if (LOWER_CASE.match(/^\w/)) {
    pages[LOWER_CASE] = {
      entry: `src/views/${_}`,
      template: [
        'works',
        'test',
        'demanddetail',
        'jobdetail',
        'myinfo',
        'user',
        'skilldetail',
        'film',
        'shareworkwall',
      ].includes(LOWER_CASE)
        ? 'public/index-adv.html'
        : 'public/index.html',
      filename: `${LOWER_CASE}.html`,
      minify: {
        removeComments: true,
        collapseWhitespace: true,
        removeAttributeQuotes: true,
      },
      chunksSortMode: (c1, c2) => {
        var order = ['chunk-vendors', LOWER_CASE];
        return order.indexOf(c1.names[0]) - order.indexOf(c2.names[0]);
      },
    };
  }

  return LOWER_CASE;
});

module.exports = {
  productionSourceMap: false,
  pages,
  publicPath: './',
  devServer: {
    port: 8000,
  },
  transpileDependencies: ['vue-lazyload'],
  configureWebpack: (config) => {
    if (isProduction) {
      // 开启gzip压缩
      config.plugins.push(
        new CompressionWebpackPlugin({
          algorithm: 'gzip',
          test: /\.js$|\.html$|\.json$|\.css/,
          threshold: 10240,
          minRatio: 0.8,
        }),
      );

      // 解决vendor过大
      // config.optimization = {
      //   runtimeChunk: 'single',
      //   splitChunks: {
      //     chunks: 'all',
      //     maxInitialRequests: Infinity,
      //     minSize: 20000000,
      //     cacheGroups: {
      //       vendor: {
      //         test: /[\\/]node_modules[\\/]/,
      //         name(module) {
      //           // get the name. E.g. node_modules/packageName/not/this/part.js
      //           // or node_modules/packageName
      //           const packageName = module.context.match(/[\\/]node_modules[\\/](.*?)([\\/]|$)/)[1];
      //           // npm package names are URL-safe, but some servers don't like @ symbols
      //           return `vendor.${packageName.replace('@', '')}`;
      //         },
      //         chunks: 'initial',
      //         priority: 2,
      //         minChunks: 2,
      //       },
      //     },
      //   },
      // };
    }
  },

  /**
   * 覆盖webpack config
   */
  chainWebpack: (config) => {
    config.resolve.extensions
      .merge(['.js', '.vue', '.json', '.less'])
      .end()
      .alias.set('@', resolve('src'))
      .set('vue$', 'vue/dist/vue.esm.js')
      .set('views', resolve('src/views'))
      .set('mixins', resolve('src/mixins'))
      .set('layout', resolve('src/layout'))
      .set('utils', resolve('src/utils'))
      .set('comp', resolve('src/components'))
      .set('assets', resolve('src/assets'))
      .set('config', resolve('src/config'))
      .set('plugins', resolve('src/plugins'));
    // 提供环境变量
    PAGES.forEach((_) => {
      if (!_) return;
      config.plugin(`html-${_}`).tap((args) => {
        args[0].isProduction = isProduction;
        return args;
      });
      config.plugins.delete(`preload-${_}`);
      config.plugins.delete(`prefetch-${_}`);
    });

    config.module.rule('eslint').delete('enforce');

    // 增加一个图片的配置
    config.module
      .rule('images')
      .use('url-loader')
      .options({
        limit: 1000,
        name: 'img/[name].[hash:8].[ext]',
      });

    config.module
      .rule('less')
      .oneOf('vue')
      .resourceQuery(/\?vue/)
      .use(['vue-style-loader', 'css-loader', 'less-loader'])
      .loader('style-resources-loader')
      .options({
        patterns: [path.resolve(__dirname, './src/assets/style/vars.less')],
      });

    config.module
      .rule('svg')
      .exclude.add(resolve('src/assets/svg'))
      .end();

    config.module
      .rule('icons')
      .test(/\.svg$/)
      .include.add(resolve('src/assets/svg'))
      .end()
      .use('svg-sprite-loader')
      .loader('svg-sprite-loader')
      .options({
        symbolId: 'icon-[name]',
      })
      .end();
  },
};
